#include "terminalform.h"
#include "ui_terminalform.h"
#include <QDebug>

TerminalForm::TerminalForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TerminalForm)
{
    ui->setupUi(this);
    cmd = new QProcess(this);

    /* 将QProcess的输出打印到界面 */
    connect(cmd,&QProcess::readyReadStandardOutput,this,&TerminalForm::on_readyReadStandardOutput);
    connect(cmd,&QProcess::readyReadStandardError,this,&TerminalForm::on_readyReadStandardError);


    /* 将QProcess的 "启动/写入/结束" 打印到界面 */
    connect(cmd,&QProcess::started,this,&TerminalForm::on_started);
    connect(cmd,&QProcess::bytesWritten,this,&TerminalForm::on_byteWritten);
    connect(cmd,SIGNAL(finished(int)),SLOT(on_finished(int)));
    // 自动启动终端解析
    start_shell();
}

TerminalForm::~TerminalForm()
{
    delete ui;
    if (cmd->state() == QProcess::Running)
    {
        cmd->terminate();
        cmd->waitForFinished();
    }
}

void TerminalForm::start_shell()
{

    if( cmd->state() == QProcess::ProcessState::Running )
    {
        ui->statusBar->setText("解析器已经启动，不用重复启动");
    }
    else
    {
        cmd->start("busybox ash");
        run_cmdstr("export Version=V1.0.0");
        ui->textEdit->append("#");
    }
}
void TerminalForm::run_cmd()
{
    // 执行输入框中的指令
    run_cmdstr(ui->lineEdit->text().toLocal8Bit() + '\n');
    // 清空输入框
    ui->lineEdit->clear();
}


void TerminalForm::run_cmdstr(QString cmd_str)
{
    if( cmd->state() != QProcess::ProcessState::Running )
    {
        ui->statusBar->setText("请启动解析器:" + cmd_str + "未执行");
        return;
    }

    cmd->waitForStarted();

    // 将指令写入cmd处理程序

    qDebug() << "#" + cmd_str.toLocal8Bit();
    ui->textEdit->append("#" + cmd_str.toLocal8Bit());
    cmd->write(cmd_str.toLocal8Bit() + '\n');

    // 清空输入框
    ui->lineEdit->clear();
}


void TerminalForm::on_readyReadStandardOutput()
{
    QString outStr = QString::fromLocal8Bit(cmd->readAllStandardOutput());
    ui->textEdit->append(outStr);
    ui->textEdit->append("#");
}

void TerminalForm::on_readyReadStandardError()
{
    QString outStr = QString::fromLocal8Bit(cmd->readAllStandardError());
    ui->textEdit->append(outStr);
    ui->textEdit->append("#");
}

void TerminalForm::on_started()
{
    ui->statusBar->setText("解析器启动正常");
}

void TerminalForm::on_byteWritten()
{
    ui->statusBar->setText("等待解析指令:"+ui->lineEdit->text());
}

void TerminalForm::on_finished(int exitCode)
{
    ui->statusBar->setText("解析器停止:退出状态 "+QString::number(exitCode));
}
